package fileDemo.imageDemo;

/**
 * @author Ajie
 * @date 2020-03-24
 * @function
 */
import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;
//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;

import java.io.*;


public class Base64Util {

    //图片转化成base64字符串---encode---md5 same. java idea macbookpro 2023-03-01 10:25:18
    public static String encodeImageToStr(String imageFilePath) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        String imgFile = imageFilePath;//待处理的图片
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }

    //base64字符串转化成图片---decode---md5 same. java idea macbookpro 2023-03-01 10:25:18
    public static boolean decodeImageToImage(String imgStr,final String imgSavePath) {
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i) {
                if(b[i]<0) {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片
            File file = new File(imgSavePath);
            if (file.exists()) {
                boolean delete = file.delete();
                if (!delete){
                    System.out.println("Base64Util:decodeImageToImage: del failed !!!!:"+imgSavePath);
                }
            }
            OutputStream out = new FileOutputStream(imgSavePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }



    //str >> base64编码后的 str
    public static String encoder(String str){
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(str.getBytes());//返回Base64编码过的字节数组字符串
    }


    //base64编码后的 str >> str
    public static byte[] decode(String str){
        //Base64解码
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = new byte[0];
        try {
            b = decoder.decodeBuffer(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for(int i=0;i<b.length;++i) {
            if(b[i]<0)
            {//调整异常数据
                b[i]+=256;
            }
        }
        return b;
    }





}

